package com.mallsystem.userservice.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageInfo;
import com.mallsystem.common.bean.RespBean;
import com.mallsystem.common.bean.User;
import com.mallsystem.common.exception.AllException;
import com.mallsystem.common.service.UserService;
import com.mallsystem.common.utils.JwtUtil;
import com.mallsystem.common.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    //注册
    @PostMapping("/reg")
    public RespBean reg(String username,String password,String passwordAgain,String captchaInput,String key) throws AllException {
        //判断验证码是否正确 - 从Redis中查询验证码进行判断
        String captcha = (String) redisUtil.get(key);
        if(captcha == null || !captcha.equalsIgnoreCase(captchaInput)){
            throw new AllException("验证码错误，请重新输入");
        }
        //判断两次输入的密码是否相同
        if(!password.equals(passwordAgain)){
            throw new AllException("2次密码不一致，请重新输入");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //注册
        userService.reg(user);
        return RespBean.ok("注册成功");
    }
    @GetMapping("/captcha")
    public RespBean captcha(){
        //创建验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 32, 4, 10);
        //生成唯一的key - 雪花算法
        String key = IdUtil.getSnowflakeNextIdStr();
        //将key 和 验证码文本保存在Redis中
        redisUtil.set(key,captcha.getCode(),60);
        //将验证码图片转换成Base64编码形式
        String imageBase64Data = captcha.getImageBase64Data();
        //将key和Base64编码保存在map中
        Map<String,Object> map = new HashMap<>();
        map.put("key",key);
        map.put("imageBase64Data",imageBase64Data);
        //将key和Base64图片返回
        return RespBean.ok("成功生成验证码",map);
    }
    @PostMapping("/login")
    public RespBean login(String username, String password,String captchaInput,String key) throws AllException {
        //判断验证码是否正确 - 从Redis中查询验证码进行判断
        String captcha = (String) redisUtil.get(key);
        if(captcha == null || !captcha.equalsIgnoreCase(captchaInput)){
            throw new AllException("验证码错误，请重新登录");
        }
        //登录
        User user = userService.login(username, password);
        //生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",user.getId());
        map.put("username",user.getUsername());
        map.put("role","user");

        String jwtStr = JwtUtil.generateJwt(map);
        //token返回给前端
        return RespBean.ok("登陆成功",jwtStr);
    }
    @GetMapping("/info")
    public RespBean getInfo(@RequestHeader("token") String token){
        //解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //获取用户id - 根据id查询用户信息
        Integer id = (Integer) map.get("id");
        User user = userService.selectById(id);
        //返回
        return RespBean.ok("",user);
    }
    @PutMapping
    public RespBean update(@RequestBody User user) throws AllException {
        userService.update(user);
        return RespBean.ok("修改成功！");
    }

    @GetMapping
    public RespBean selectByPage(User condition, Integer pageNum, Integer pageSize){
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 1 : pageSize;
        PageInfo<User> pageInfo = userService.selectByCondition(condition, pageNum, pageSize);
        return RespBean.ok("查询成功",pageInfo);
    }
    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") Integer id){
        User user = userService.selectById(id);
        return RespBean.ok("查询成功",user);
    }
    //修改所有密码
    @GetMapping("/allpassword")
    public RespBean updateAllPassword(Integer id,String password,String payPassword) throws AllException {
        userService.updateAllPassword(id,password,payPassword);
        return RespBean.ok("成功修改密码");
    }
    //修改状态

    @PutMapping("/status")
    //@RequestMapping(value = "/status",method = RequestMethod.PUT)
    public RespBean updateStatus(@RequestBody User user) throws AllException {
        userService.updateStatus(user);
        return RespBean.ok("成功修改状态");
    }
    @PutMapping("/password")
    public RespBean updatePassword(String oldPwd,String newPwd,String newPwdAgain,@RequestHeader("token") String token) throws AllException {
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        if(!newPwd.equals(newPwdAgain)){
            throw new AllException("两次密码不一致，请确认后重新输入");
        }
        userService.updatePassword(userId,newPwd,oldPwd);
        return RespBean.ok("成功修改登录密码 ！！请重新登陆~~");
    }
    @PutMapping("/payPwd")
    public RespBean updatePayPassword(String oldPayPwd,String newPayPwd,String newPayPwdAgain,@RequestHeader("token") String token) throws AllException {
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        if(!newPayPwd.equals(newPayPwdAgain)){
            throw new AllException("两次密码不一致，请确认后重新输入");
        }
        userService.updatePayPassword(userId,newPayPwd,oldPayPwd);
        return RespBean.ok("成功修改支付密码 ！！");
    }
    @PutMapping("/recharge")
    public RespBean recharge(Integer sum,@RequestHeader("token") String token) throws AllException {
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        BigDecimal s = new BigDecimal(sum);
        userService.recharge(userId,s);
        return RespBean.ok("充值成功!!!");
    }
}
